import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    cart: [],
    products: [
      { id: 1, name: '手机', price: 2000 },
      { id: 2, name: '母鸡', price: 20 },
      { id: 3, name: '飞机', price: 20000000 }
    ]
  },
  getters: {
    cartTotal: state => {
      return state.cart.reduce((total, product) => {
        return total + product.price * product.quantity
      }, 0)
    }
  },
  mutations: {
    addToCart(state, productId) {
      const product = state.products.find(p => p.id === productId)
      const cartItem = state.cart.find(item => item.id === productId)
      
      if (cartItem) {
        cartItem.quantity++
      } else {
        state.cart.push({ ...product, quantity: 1 })
      }
    },
    removeFromCart(state, productId) {
      state.cart = state.cart.filter(item => item.id !== productId)
    },
    decreaseQuantity(state, productId) {
      const cartItem = state.cart.find(item => item.id === productId)
      if (cartItem && cartItem.quantity > 1) {
        cartItem.quantity--
      } else {
        state.cart = state.cart.filter(item => item.id !== productId)
      }
    }
  },
  actions: {
    addToCart({ commit }, productId) {
      commit('addToCart', productId)
    },
    removeFromCart({ commit }, productId) {
      commit('removeFromCart', productId)
    },
    decreaseQuantity({ commit }, productId) {
      commit('decreaseQuantity', productId)
    }
  },
  modules: {
  }
})